package jgcp.worker;

/**
 * @author Peng Zhang
 */
import java.util.*;
import java.io.*;

public class TaskDispatcher implements TaskQueueObserver {
	
	private ArrayList <Process> processList = new ArrayList();
	private ArrayList <Task> taskList = new ArrayList();
	
	
	
	public void update(Task t){
		
		
	    new TaskThread(t).start();
	}
	
	
	public void cancelTask(Task t){
		Process p = processList.get(taskList.indexOf(t));
		taskList.remove(t);
		processList.remove(p);
		p.destroy();
		System.out.println("Canceled from processlist");
	}
	
	/*
	 * return current processed tasks
	 */
	public ArrayList processedTasks(){
		return taskList;
	}
	
	/*
	 * inner Class TaskThread maintains each task in a separate JVM
	 */
	class TaskThread  extends Thread{
		
		private Process process;
		private Task task;
		private String cmd;
		public TaskThread(Task t){
			task = t;
			if(t.getType().equalsIgnoreCase("exe")){
				cmd = ".//tasks//"+t.getTaskFullName();
			}else if(t.getType().equalsIgnoreCase("jar")){
				cmd = "java -jar .//tasks//"+t.getTaskFullName();
			}
			
		}
		public void run(){
			
			try {
				
				try {
					process = (Process) Runtime.getRuntime().exec(cmd);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				processList.add(process);
				taskList.add(task);
				 
                writeResult(process.getInputStream(),task.getTaskID());
                System.out.println("save result");
				process.waitFor();
				taskList.remove(processList.indexOf(process));
				processList.remove(process);
				
				System.out.println(taskList);
				//System.out.println(process);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		/*
		 *  save the result of task computation to temporary file 
		 */
		public void writeResult(InputStream in, int id){
			
			String temp = null;
			String result = null;
			try {
				InputStreamReader ir = new InputStreamReader(in);
				BufferedReader bResult = new BufferedReader(ir);
				do{
					temp = bResult.readLine();
					result = temp + result;
				}while((temp = bResult.readLine())!=null);
				
				FileOutputStream fos = new FileOutputStream(".//Result//" + id + ".txt");
				Writer out = new OutputStreamWriter(fos, "UTF8");
				out.write(result);
				//System.out.println("save result");
				out.close();
			    } catch (IOException e) {
				e.printStackTrace();
			    }

		}
	}

}
